package cn.dxh.stagefinal.controller;

import cn.dxh.stagefinal.bean.Employee;
import cn.dxh.stagefinal.service.LoginService;
import cn.dxh.stagefinal.utils.BaseWriteInfo;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 2019/12/11 11:39
 *
 * @author Wenhao Lee
 * 心向远方，不负厚望。
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/user/login.do")
    public void login(String loginName, String password, String saveCookie,
                      HttpServletRequest request, HttpServletResponse response,
                      @RequestParam(defaultValue = "false") boolean isAuto) throws IOException {
        System.out.println(isAuto);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Employee employee = loginService.login(loginName, password);
            if (employee != null) {
                if (!isAuto) {
                    //如果当前不是自动登录 先清除cookie 然后再保存
                    for (Cookie cookie : request.getCookies()) {
                        cookie.setMaxAge(0);
                    }
                    Cookie loginNameCookie = new Cookie("loginName", URLEncoder.encode(loginName, "UTF-8"));
                    Cookie pwdCookie = new Cookie("pwd", URLEncoder.encode(password, "UTF-8"));
                    loginNameCookie.setPath("/");
                    pwdCookie.setPath("/");
                    switch (saveCookie) {
                        case "Day":
                            loginNameCookie.setMaxAge(60 * 60 * 24);
                            pwdCookie.setMaxAge(60 * 60 * 24);
                            break;
                        case "Month":
                            loginNameCookie.setMaxAge(60 * 60 * 24 * 30);
                            pwdCookie.setMaxAge(60 * 60 * 24 * 30);
                            break;
                        case "Year":
                            loginNameCookie.setMaxAge(60 * 60 * 24 * 30 * 12);
                            pwdCookie.setMaxAge(60 * 60 * 24 * 30 * 12);
                            break;
                        default:
                            loginNameCookie.setMaxAge(0);
                            pwdCookie.setMaxAge(0);
                            break;
                    }
                    response.addCookie(loginNameCookie);
                    response.addCookie(pwdCookie);
                }
                HttpSession session = request.getSession();
                String ip = request.getRemoteAddr();
                session.setAttribute("currentUser", employee);
                session.setAttribute("loginIp", ip);
                session.setAttribute("loginTime", new Date());
                out.println(String.format(BaseWriteInfo.ALERT_AND_REDIRECT, "登录成功", "/index"));
            } else
                out.println(String.format(BaseWriteInfo.ALERT_AND_BACK, "登陆失败"));
        } catch (UnknownAccountException e) {
            out.println(String.format(BaseWriteInfo.ALERT_AND_BACK, "很抱歉，无法找到该用户:" + loginName));
        } catch (IncorrectCredentialsException e) {
            out.println(String.format(BaseWriteInfo.ALERT_AND_BACK, "密码错误，请重试"));
        } catch (Exception e) {
            out.println(String.format(BaseWriteInfo.ALERT_AND_BACK, "未知异常"));
        }
    }

    @RequestMapping("/user/autoLogin.do")
    public String autoLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("执行自动登录方法");
        String loginName = null;
        String loginPwd = null;
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();
        if (cookies.length == 0) {
            System.out.println("Cookie长度为0");
            return "/login";
//            out.println(String.format(BaseWriteInfo.REDIRECT, "/toLogin"));
//            return;
        }
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName());
            if (cookie.getName().equals("loginName")) {
                loginName = cookie.getValue();
            }
            if (cookie.getName().equals("pwd")) {
                loginPwd = cookie.getValue();
            }
        }
        if (loginName == null || loginPwd == null) {
            System.out.println("自动登录缺少必要信息");
            return "/login";
        }
        login(loginName, loginPwd, null, request, response, true);
        return null;
    }

    @RequestMapping("/cleanCookie.do")
    public void cleanCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("执行清除cookie操作");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            System.out.println("没有cookie，直接去退出");
            out.print(String.format(BaseWriteInfo.REDIRECT, "/user/logout.do"));
            return;
        }
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName());
            //设置cookie当场死亡
            cookie.setMaxAge(0);
            cookie.setDomain("");
            cookie.setPath("");
            response.addCookie(cookie);
        }
        out.print(String.format(BaseWriteInfo.REDIRECT, "/user/logout.do"));
    }

}
